import EventEmitter from '@/lib/core/EventEmitter';

export default class JpushVipUtils {
    private static instance: JpushVipUtils;

    public static getInstance() {
        if (!this.instance) {
            this.instance = new JpushVipUtils();
        }
        return this.instance;
    }

    private mJpushVip: ApicloudModules['jpushVip'];

    private constructor() {
        this.mJpushVip = api.require('jpushVip')
        if (!this.mJpushVip) {
            throw new Error('jpushVip 模块没引入')
        }
    }
    /**
     * 初始化极光推送
     * @returns ios直接返回true，android看初始化回调
     */
    public init() {
        return new Promise<boolean>((resolve) => {
            if (api.systemType === 'android') {
                this.mJpushVip.init((ret) => {
                    resolve(ret.status);
                });
            } else {
                resolve(true);
            }
        });
    }
    /**
     * 绑定别名和标签
     * @param alias 别名字符串
     * @param tags  标签字符串数组
     * @returns 返回极光推送状态码
     */
    public bindAliasAndTags(params: { alias?: string, tags?: string[] }) {
        return new Promise<number>((resolve) => {
            this.mJpushVip.bindAliasAndTags(params, (ret) => {
                resolve(ret.statusCode);
            })
        });
    }
    /**
     * 清除极光推送发送到状态栏的通知。
     * @param id  待清除的通知id（等同于消息ID），为-1时清除所有，iOS只支持清除所有，不能为空
     */
    public clearNotification(params?: { id: number | -1 }) {
        return new Promise<boolean>((resolve) => {
            this.mJpushVip.clearNotification(params || { id: -1 }, (ret) => {
                resolve(ret.status === 1);
            });

        });
    }
    /**
     * 获取设备的标识
     */
    public getRegistrationId() {
        return new Promise<string>((resolve) => {
            this.mJpushVip.getRegistrationId((ret) => {
                resolve(ret.id);
            })
        });
    }
    /**
     * 设置监听通知被点击事件
     */
    public setNoticeclickedListener(callback: (extra: { [key: string]: any }) => void) {
        if (api.systemType === 'android') {

            EventEmitter.onSystem({
                name: 'appintent' as any
            }, (ret) => {
                if (ret && ret.appParam.ajpush) {
                    const ajpush = ret.appParam.ajpush;
                    const extra = ajpush.extra;
                    callback(extra);
                }
            });
        } else {

            EventEmitter.onSystem({
                name: 'noticeclicked' as any
            }, (ret) => {
                if (ret && ret.value) {
                    const ajpush = ret.value;
                    const extra = ajpush.extra;
                    callback(extra);
                }
            });
        }
    }
}
